package com.terenac;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;


import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ChatForm extends Activity{

	private ArrayList<String> messages = new ArrayList();
    private Handler mHandler = new Handler();
    private EditText mSendText;
    private ListView mList;
    private String oznaceni;
    private XMPPConnection connection;
    private Collection<RosterEntry> korisnici;
    private ArrayList<String> imena = new ArrayList();

	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		
		
		// stvaranje konekcije
		this.connection = new XMPPConnection("pazin.ice.hr");
		
		this.connectToChat();
		
        this.mSendText = (EditText) findViewById(R.id.unosTeksta);
        this.mList = (ListView) findViewById(R.id.poruke);
        
        
        
		setListAdapter2();

		Button send = (Button) findViewById(R.id.salji);
        send.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                String text = mSendText.getText().toString();
                
                if (text.length() != 0){
	                Message msg = new Message(oznaceni, Message.Type.chat);
	                msg.setBody(text);
	                try{
	                	connection.sendPacket(msg);
	                }catch(Exception e){
	                	connectToChat();
	                	connection.sendPacket(msg);
	                }
	                messages.add(0,connection.getUser().split("/")[0] + ": " + text);
	                setListAdapter2();
	                mSendText.setText("");
                }
            }
        });
        
        Button otvoriKontakt = (Button) findViewById(R.id.otvorikontakte);
        otvoriKontakt.setOnClickListener(new OnClickListener() {
        	public void onClick(View view) {
        		 
        		 RelativeLayout sve = (RelativeLayout) findViewById(R.id.mainchat);
        		 ListView nesto = (ListView) findViewById(R.id.neka_lista);	
        		 korisnici = getRoster().getEntries();
        		 imena.clear();
        	        for (RosterEntry entry : korisnici) {
        	            imena.add(entry.getUser());
        	        }

        		 KontaktiAdapter adapter2 = new KontaktiAdapter(
     					getApplicationContext(), R.layout.kontakti, imena);
        		 nesto.setAdapter(adapter2);
        		 sve.setVisibility(LinearLayout.GONE);
        		 nesto.setVisibility(View.VISIBLE);
        		 nesto.bringToFront();
        		 nesto.setOnItemClickListener(new OnItemClickListener(){
        			 public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        				 oznaceni = (String) parent.getItemAtPosition(position);
        				 RelativeLayout sve = (RelativeLayout) findViewById(R.id.mainchat);
                		 ListView nesto = (ListView) findViewById(R.id.neka_lista);	
        				 nesto.setVisibility(LinearLayout.GONE);
                		 sve.setVisibility(View.VISIBLE);
                		 sve.bringToFront();
        			 }

        		 });
        		 
        	}
        });
		
	}
	
	public void setConnection(XMPPConnection connection) {
		this.connection = connection;
		if (connection != null) {
			// Add a packet listener to get messages sent to us
			PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
			connection.addPacketListener(new PacketListener() {
				public void processPacket(Packet packet) {
					Message message = (Message) packet;
					if (message.getBody() != null) {
						String fromName = StringUtils.parseBareAddress(message.getFrom());
						messages.add(0,fromName + ": " + message.getBody());
						// Add the incoming message to the list view
						mHandler.post(new Runnable() {
							public void run() {
								setListAdapter2();
							}
						});
					}
				}
			}, filter);
		}
	}
	private void setListAdapter2() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.liste,
				messages);
		mList.setAdapter(adapter);
	}
	
	public Roster getRoster() {
		Roster temp;
		try{
			temp = this.connection.getRoster();
        }catch(Exception e){
        	connectToChat();
        	temp = this.connection.getRoster();
        }
		return temp;
	}
	
	private void connectToChat(){

		try{
			this.connection.connect();
		}catch(XMPPException ex){
			this.connection = null;
		}
		try{
			this.connection.login(User.getUsername(), User.getPassword());
			Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);
            this.setConnection(this.connection);
		}catch(XMPPException ex){
			this.connection = null;
		}
	}
		
}

